package com.artron.mediaartron.ui.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.widget.ImageView;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-09-28.
 */

public class CustomImageView extends ImageView {

    private ViewPager mParentPager;


    private OnUpdateDrawableCallback mOnUpdateDrawableCallback;

    public CustomImageView(Context context) {
        super(context);
    }

    public CustomImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touchEvent();
                break;
            case MotionEvent.ACTION_MOVE:
                return false;
        }
        return super.onTouchEvent(event);
    }


    public void setParentPager(ViewPager pager) {
        this.mParentPager = pager;
    }

    private void touchEvent() {
        if (mParentPager != null && mParentPager instanceof CustomVerticalViewPager) {
            ((CustomVerticalViewPager) mParentPager).onTouchEvent();
        }
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        if (drawable != null && mOnUpdateDrawableCallback != null) {
            mOnUpdateDrawableCallback.updateDrawable(drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
        }
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        if (bm != null && mOnUpdateDrawableCallback != null) {
            DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
            mOnUpdateDrawableCallback.updateDrawable(bm.getScaledWidth(displayMetrics),
                    bm.getScaledHeight(displayMetrics));
        }
    }

    public interface OnUpdateDrawableCallback {
        void updateDrawable(int width, int height);
    }

    public void setOnUpdateDrawableCallback(OnUpdateDrawableCallback onUpdateDrawableCallback) {
        mOnUpdateDrawableCallback = onUpdateDrawableCallback;
    }

}
